# -*- coding: utf-8 -*-

from core.serializers import CustomModelSerializer
from core.relations import BaseNameWritableRelatedField
from apps.rms.models import PacketType, PacketField
from rest_framework import serializers


class PacketTypeSerializer(CustomModelSerializer):
    """
    网络协议-序列化器
    """
    product = BaseNameWritableRelatedField()
    field_count = serializers.SerializerMethodField(read_only=True)

    def get_field_count(self, instance):
        return len(PacketField.objects.filter(packet=instance.id))

    class Meta:
        model = PacketType
        fields = "__all__"
        read_only_fields = ["id"]

class PacketFieldSerializer(CustomModelSerializer):
    """
    协议字段-序列化器
    """
    product = BaseNameWritableRelatedField()
    packet = BaseNameWritableRelatedField()

    class Meta:
        model = PacketField
        fields = "__all__"
        read_only_fields = ["id"]


class PacketFieldBindingSerializer(CustomModelSerializer):
    """
    协议字段-序列化器
    """
    product = BaseNameWritableRelatedField()
    packet = BaseNameWritableRelatedField()

    class Meta:
        model = PacketField
        fields = ['name','desc','packet','product']
        read_only_fields = ["id"]

class PacketTreeSelectSerializer(CustomModelSerializer):
    """
    树型协议字段-序列化器
    """
    children=serializers.SerializerMethodField()

    def get_children(self,instance):
        queryset = PacketField.objects.filter(packet=instance.id)
        return PacketFieldSerializer(queryset,many=True,request=self.request).data

    class Meta:
        model=PacketType
        fields=('id','name','children')
        read_only_fields=["id"]